package com.hotkidceo.springcloud.base;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

/**
 * member login ?
 */
public class LoggedinInterceptor extends HandlerInterceptorAdapter {

	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
		HandlerMethod handlerMethod = (HandlerMethod) handler;
		IsLoggedin isLoggedin = handlerMethod.getMethodAnnotation(IsLoggedin.class);
		// 沒有註解不用判斷
		if (isLoggedin == null) {
			return true;
		}
		else {
			// 若沒有會話或會員，則返回"會員未登錄"
			if (request.getSession(false) == null || request.getSession(false).getAttribute("member") == null) {
				response.setContentType("application/json");
				response.setCharacterEncoding("UTF-8");
				response.getWriter().print("{\"error\":\"會員未登錄\"}");
				response.flushBuffer();
				return false;
			}
			else {
				return true;
			}
		}
	}
}
